import java.util.Arrays;

/**
 * This class is a subclass of the Hand class, and are used to model a hand of Straight. 
 * It overrides getTopCard,isValid and getType method that it inherits from Hand class.
 *
 * @author Jiang Feiyu
 *
 */
public class Straight extends Hand{

    /**
     * Constructor for the Straight type hand. Calls the constructor of Hand superclass.
     *
     * @param player Player who plays the hand
     * @param cards  List of card played by the player
     */
    public Straight(CardGamePlayer player, CardList cards) {
        super(player, cards);
    }

    /**
     * Returns the top card of the hand.
     * The card with the highest rank in a straight is referred to as the top card of this straight.
     */
    public Card getTopCard() {
        int returnIndex = 0;
        int largest_card = 0;
        for(int i = 0;i < 5;i ++) {
            int this_rank = 0;
            if (this.getCard(i).getRank() == 0){
                this_rank = 13;
            }
            if (this.getCard(i).getRank() == 1){
                this_rank = 14;
            }
            if (this_rank > largest_card){
                largest_card = this_rank;
                returnIndex = i;
            }
        }
        return this.getCard(returnIndex);
    }


    /**
     * Checks whether the hand is a Straight.
     */
    public boolean isValid() {
        //check whether the total number is right

        if(this.size() == 5) {
            // initialize hand rank
            int[] handranks = new int[5];
            for (int i = 0; i < handranks.length; i ++){
                handranks[i] = this.getCard(i).getRank();
            }
            // Sort rank A and 2
            for(int i =0;i < 5; i++) {
                int handrank = handranks[i];
                switch (handrank) {
                    case 0:
                        handranks[i] = 13;
                    case 1:
                        handranks[i] = 14;
                    default:
                        handranks[i] = handrank;
                }
            }
            // check whether it is consecutive
            Arrays.sort(handranks);
            for(int i = 0;i < 4;i++){
                if (i == 3){
                    return handranks[i] == handranks[i + 1];
                }
                else{
                    if (handranks[i] != handranks[i + 1]){
                        return false;
                    }
                }
            }
        }
        // if the number of cards not right
        else{
            return false;
        }
        return false;
    }

    /**
     * Returns type of string.
     */
    public String getType() {
        return "Straight";
    }
}